/**
 * 
 */
package com.wxq.weitool;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.stream.Collectors;

import org.springframework.beans.BeanUtils;

/**
 * @author West.W
 * create date 2018-01-26 13:57:54
 */

public class Collections {
	
	/**
	 * @return ArrayList实例
	 */
	public static <E> List<E> list(){
		return new ArrayList<>();
	}
	/**
	 * @return HashSet实例
	 */
	public static <E> Set<E> set(){
		return new HashSet<>();
	}
	
	/**
	 * @return HashMap实例
	 */
	public static <K,V> Map<K,V> map(){
		return new HashMap<>();
	}	     
	/**
	 * @return LinkedHashMap
	 */
	public static <K,V> Map<K,V> linkedMap(){
		return new LinkedHashMap<>();
	}	     
	/**
	 * @return ConcurrentHashMap
	 */
	public static <K,V> Map<K,V> concurrentMap(){
		return new ConcurrentHashMap<>();
	}	     
    /**
     * 循环 <code>beanCollection</code>,将元素使用<code>keyTransformer</code>转成key
     * ,相同值的元素组成list作为value,封装成map返回.
     * 
     * @param <K>
     *            the key type
     * @param <E>
     *            the element type
     * @param collection
     *            bean collection,诸如List{@code <User>},Set{@code <User>}等
   
     * @param keyTransformer
     *            返回的map,key转换器
     * @return 符合条件元素的分组<br>
     */
	  public static <K, E> Map<K, List<E>> group(Collection<E> beanCollection,Function<E,K> keyTransformer){
		 if (beanCollection == null) {
			return new HashMap<>();
		}
		  return beanCollection.stream()
		  .collect(Collectors.groupingBy(keyTransformer));
		  
		  
	  }
	  
	  /**bean集合转map
	 * @param <E> bean类型
	 * @param <K> 转换后的键类型
	 * @param <V> 转换后的值类型
	 * @param beanCollection 诸如List{@code <User>},Set{@code <User>}等
	 * @param keyMapper 键获取函数
	 * @param valueMapper 值获取函数
	 * @return
	 */
	public static <E,K,V> Map<K,V> toMap(Collection<E> beanCollection,Function<E,K> keyMapper,
              Function<E,V> valueMapper) {
		  return beanCollection.stream()
		  .collect(Collectors.toMap(keyMapper, valueMapper));
		  
	  }
	
	public static <S,T>	List<T> copyBeans(List<S> source,Class<T> targetClass){
		List<T> list = list();
		for (S s : source) {
			T target;
			try {
				target = targetClass.newInstance();
			} catch (Exception e ) {
				throw new RuntimeException("bean 初始化异常");
			} 
			BeanUtils.copyProperties(s, target);
			list.add(target);
			
		} 
		return list;
	}
}
